<?php defined('SYSPATH') OR die('No direct access allowed.');

class Reset_Password_Controller extends Template_Controller 
{
	public $template = 'reset_password';
	public $content = 'reset_password_content';
	
	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		$this->template->title = '重置密码!';	
		$password_check = $this->input->get('p');
		if (!empty($password_check) AND $this->check_code($password_check))
		{
			
		}
		else
		{
			url::redirect();
		}
	}

	public function change_password()
	{
		$this->template->title = '重置密码!';
		if ($post = $this->input->post())
		{
			$password_check = $this->input->post('password_check');
			$password = $this->input->post('password');
			$password_confirmation = $this->input->post('password_confirmation');
			$array = explode(' &',base64_decode($password_check));
			print Kohana::Debug($password_check);
			print Kohana::Debug($password);
			print Kohana::Debug($password_confirmation);
			if (!$this->check_code($password_check))
			{
				url::redirect();
			}
			$user = ORM::factory('user');
			$find_user = $user->where('email', $array['0'])->find();
			$array_change_password = array('password' => $password, 'password_confirm' => $password_confirmation);
			if ($find_user->change_password($array_change_password))
			{
				$find_user->save();
				url::redirect('login');
			}
		}
		else
		{
		}
	}

	protected function check_code($password_check)
	{
		$array = explode(' &',base64_decode($password_check));
		print Kohana::Debug($array);
		$user = ORM::factory('user');
		$find_user = $user->where('email', $array['0'])->find();
		if ($find_user->loaded)
		{
			$checkCode = md5($array['0'].'+'.$find_user->password);
			if( $array['1'] === $checkCode )
			{
				$this->template->content->password_check = $password_check;
				$this->template->content->email = $find_user->email;
				return true;
			}
		}
		return false;
	}
}
